package com.demo.crm.springboot3security.validation;

import org.springframework.stereotype.Component;

import com.demo.crm.springboot3security.entity.FormRelation;
import com.demo.crm.springboot3security.entity.enums.RelationType;
import com.demo.crm.springboot3security.exception.FormRelationException;
import com.demo.crm.springboot3security.service.CustomFormService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@RequiredArgsConstructor
public class FormRelationValidator {

    private final CustomFormService customFormService;
    // private final FormRelationService formRelationService;

    public void validateFormRelation(FormRelation relation) {
        log.debug("开始验证表单关系: {}", relation);

        // 基本非空验证
        validateNotNull(relation);

        // 验证表单ID
        validateFormIds(relation);

        // 验证关系类型
        validateRelationType(relation.getType());

        // 验证源表单和目标表单不能相同
        validateDifferentForms(relation);

        // 验证关系配置
        // validateRelationConfig(relation);

        // 验证是否存在重复关系
        validateDuplicateRelation(relation);

        log.debug("表单关系验证通过");
    }

    private void validateNotNull(FormRelation relation) {
        if (relation == null) {
            throw new FormRelationException.InvalidRelationException("表单关系不能为空");
        }

        if (relation.getSourceFormId() == null) {
            throw new FormRelationException.InvalidRelationException("源表单ID不能为空");
        }

        if (relation.getTargetFormId() == null) {
            throw new FormRelationException.InvalidRelationException("目标表单ID不能为空");
        }

        if (relation.getType() == null) {
            throw new FormRelationException.InvalidRelationException("关系类型不能为空");
        }
    }

    private void validateFormIds(FormRelation relation) {
        var sourceForm = customFormService.findById(relation.getSourceFormId());
        if (sourceForm == null) {
            throw new FormRelationException.InvalidRelationException("源表单不存在");
        }
        if (!sourceForm.isPublished()) {
            throw new FormRelationException.InvalidRelationException("源表单未发布，不能建立关系");
        }

        var targetForm = customFormService.findById(relation.getTargetFormId());
        if (targetForm == null) {
            throw new FormRelationException.InvalidRelationException("目标表单不存在");
        }
        if (!targetForm.isPublished()) {
            throw new FormRelationException.InvalidRelationException("目标表单未发布，不能建立关系");
        }
    }

    public void validateRelationType(RelationType relationType) {
        try {
            log.debug("验证关系类型: {}, 描述: {}", relationType, relationType.getDescription());
        } catch (IllegalArgumentException e) {
            log.warn("无效的关系类型: {}", relationType);
            throw new FormRelationException.InvalidRelationException("无效的关系类型: " + relationType);
        }
    }

    private void validateDifferentForms(FormRelation relation) {
        if (relation.getSourceFormId().equals(relation.getTargetFormId())) {
            throw new FormRelationException.InvalidRelationException("源表单和目标表单不能相同");
        }
    }

    // private void validateRelationConfig(FormRelation relation) {
    // if (relation.getRelationConfig() != null &&
    // !relation.getRelationConfig().trim().isEmpty()) {
    // try {
    // // 验证关系配置是否为有效的JSON
    // com.fasterxml.jackson.databind.ObjectMapper mapper = new
    // com.fasterxml.jackson.databind.ObjectMapper();
    // mapper.readTree(relation.getRelationConfig());
    // } catch (Exception e) {
    // log.warn("关系配置JSON格式无效: {}", relation.getRelationConfig());
    // throw new FormRelationException.InvalidRelationException("关系配置必须是有效的JSON格式");
    // }
    // }
    // }

    private void validateDuplicateRelation(FormRelation relation) {
        // if (relation.getId() == null &&
        // formRelationService.existsBySourceAndTargetForm(relation.getSourceFormId(),
        // relation.getTargetFormId())) {
        // throw new FormRelationException.DuplicateRelationException(
        // String.format("源表单(%d)和目标表单(%d)之间已存在关系", relation.getSourceFormId(),
        // relation.getTargetFormId()));
        // }
    }

    public void validateBatchOperation(Iterable<?> items) {
        if (items == null) {
            throw new FormRelationException.InvalidRelationException("批量操作数据不能为空");
        }

        if (!items.iterator().hasNext()) {
            throw new FormRelationException.InvalidRelationException("批量操作数据列表不能为空");
        }

        int count = 0;
        for (Object item : items) {
            count++;
            if (count > 1000) {
                throw new FormRelationException.InvalidRelationException("批量操作数据不能超过1000条");
            }
        }
        log.debug("批量操作数据验证通过，共{}条数据", count);
    }
}